﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Xml;
using nwrole.Module.lib;

namespace nwrole.ModuleService
{
    public partial class ModuleService : ServiceBase
    {
        //private PluginServiceHost pluginServiceHost;

        //private ConsoleLogWriter consoleLogWriter = new ConsoleLogWriter();

        protected IModule _module;
        protected IModuleDebug _debug;

        protected XmlDocument _config;

        public ModuleService()
        {
            //pluginServiceHost = new PluginServiceHost(pluginProviderClassName, id, serviceName, port, supervisorPort);
            
            InitializeComponent();

            //Console.SetOut(consoleLogWriter);

            _debug = new ModuleDebug();

            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string filePath = Path.Combine(path, "config.xml");
            _config = new XmlDocument();
            _config.Load(filePath);
            
            XmlNode moduleNode = _config.SelectSingleNode("/Config/Module");
            string className = moduleNode.Attributes["className"].ToString();
            
            CreateModule(className);
        }

        protected override void OnStart(string[] args)
        {
            //pluginServiceHost.Start();
            _module.Start(_debug, /*_config*/ null);
        }

        protected override void OnStop()
        {
            //pluginServiceHost.Stop();
            _module.Stop();
        }

        protected void CreateModule(string className)
        {
            Type type = Type.GetType(className);
            _module = (IModule)Activator.CreateInstance(type);
        }
    }
}
